// Copyright 2006 Nokia Corporation.
//
// THIS SOURCE CODE IS PROVIDED 'AS IS', WITH NO WARRANTIES WHATSOEVER,
// EXPRESS OR IMPLIED, INCLUDING ANY WARRANTY OF MERCHANTABILITY, FITNESS
// FOR ANY PARTICULAR PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE
// OR TRADE PRACTICE, RELATING TO THE SOURCE CODE OR ANY WARRANTY OTHERWISE
// ARISING OUT OF ANY PROPOSAL, SPECIFICATION, OR SAMPLE AND WITH NO
// OBLIGATION OF NOKIA TO PROVIDE THE LICENSEE WITH ANY MAINTENANCE OR
// SUPPORT. FURTHERMORE, NOKIA MAKES NO WARRANTY THAT EXERCISE OF THE
// RIGHTS GRANTED HEREUNDER DOES NOT INFRINGE OR MAY NOT CAUSE INFRINGEMENT
// OF ANY PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OWNED OR CONTROLLED
// BY THIRD PARTIES
//
// Furthermore, information provided in this source code is preliminary,
// and may be changed substantially prior to final release. Nokia Corporation
// retains the right to make changes to this source code at
// any time, without notice. This source code is provided for informational
// purposes only.
//
// Nokia and Nokia Connecting People are registered trademarks of Nokia
// Corporation.
// Java and all Java-based marks are trademarks or registered trademarks of
// Sun Microsystems, Inc.
// Other product and company names mentioned herein may be trademarks or
// trade names of their respective owners.
//
// A non-exclusive, non-transferable, worldwide, limited license is hereby
// granted to the Licensee to download, print, reproduce and modify the
// source code. The licensee has the right to market, sell, distribute and
// make available the source code in original or modified form only when
// incorporated into the programs developed by the Licensee. No other
// license, express or implied, by estoppel or otherwise, to any other
// intellectual property rights is granted herein.
package bcexchanger.ui;

import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.List;

import bcexchanger.*;

/**
 * 
 * This class represents a screen displaying the list of contacts of
 * the address book. The user can either choose the one contact or
 * exit the application
 * 
 * This class peforms the reading of address book entries in the 
 * separate thread, because reading the long address book might
 * take significant time
 * 
 * The class is extending an example.BCExchanger.ui.Screen class and
 * implements Runnable interface.
 * 
 * @see example.BCExchanger.ui.Screen Design patterns: State
 */
public class AddressBookScreen extends Screen implements Runnable {

  private Vector names;
  private Vector uids;
  private List list;
  private Command okCommand;
  private Command exitCommand;

  private Gauge gauge;
  private Form progressBar;
  private Thread thread;
  private Command progressExitCommand;
  
  /**
   * Constructor
   * 
   * @param _midlet -
   *          the parent class which keeps the current UI state
   */
  public AddressBookScreen(BCExchangerMIDlet _midlet) {
    super(_midlet);
   
    // create and add commands to ui list
    progressBar = new Form("Please wait");

    gauge = new Gauge("Reading contacts", false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING);
    gauge.setLayout(Item.LAYOUT_CENTER);
    gauge.setLayout(Item.LAYOUT_VCENTER);
    progressBar.append(gauge);
    
    progressExitCommand = new Command("Exit", Command.EXIT, 1);
    progressBar.addCommand(progressExitCommand);

    progressBar.setCommandListener(this);

    displayable = progressBar;


    // start the thread reading the address book entries
    thread = new Thread(this);
    thread.start();
    
  }

  public void commandAction(Command command, Displayable _displayable) {

    // in case this callback is called from wrong displayble
    if (_displayable != list && _displayable != progressBar) {
      throw new RuntimeException(
          "Internal error #14: AddressBookScreen.commandAction()");
    }

    if (command == okCommand) {

      String uid = null;

      // determine the index
      try {
        uid = (String) uids.elementAt(list.getSelectedIndex());
      } catch (Exception e) {
        throw new RuntimeException("Internal error #15");
      }

      // save UID of the chosen card
      try {
        Storage.setBCUID(uid);
        midlet.changeScreen(new MainScreen(midlet));
      } catch (Exception e1) {
        midlet.changeScreen(new AlertMessage(midlet,
            "Cannot save own business card", null));
      }
    } else if (command == exitCommand || command == progressExitCommand) {
      midlet.quit();
    } else {
      // unknown command
      throw new RuntimeException("Internal error #20");
    }
  }

  /* (non-Javadoc)
   * @see java.lang.Runnable#run()
   */
  public void run() {
    
    // get the list of names and UIDs
    Vector[] v;
    try {
      v = AddressBook.getNamesUIDLists();
      names = v[0];
      uids = v[1];
    } catch (Exception e) {
      midlet.changeScreen(new AlertMessage(midlet,
          "Cannot read contact list data. Application will exit")); // quit
                                                                    // after
                                                                    // this
                                                                    // alert
      return;
    }

    // create a UI list of names
    list = new List("Choose own business card", List.EXCLUSIVE);

    Enumeration e = names.elements();
    if (!e.hasMoreElements()) { // names list is empty
      midlet
          .changeScreen(new AlertMessage(
              midlet,
              "Contact list is empty. Please create own contact. Application will exit")); // quit
                                                                                            // after
                                                                                            // this
                                                                                            // alert

      return;
    } else {
      while (e.hasMoreElements()) {
        // browse through names list and
        // add them to ui list
        list.append((String) e.nextElement(), null);
      }

      // create and add commands to ui list
      okCommand = new Command("Ok", Command.OK, 1);
      exitCommand = new Command("Exit", Command.EXIT, 1);

      list.addCommand(okCommand);
      list.addCommand(exitCommand);

      list.setCommandListener(this);

      displayable = list;

      midlet.changeScreen(this);
	
    }
    
  }
}
